package com.grf.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import java.util.HashMap;

@Configuration
@EnableKafka
@PropertySource(value = {"kafka.properties"})
public class KafkaProducerConfig {
    @Value("${kafka.bootstrap_servers}")
    private String bootstrap_servers;
    @Value("${kafka.retries}")
    private String retries;
    @Value("${kafka.batch_size}")
    private String batch_size;
    @Value("${kafka.linger_ms}")
    private String linger_ms;
    @Value("${kafka.buffer_memory}")
    private String buffer_memory;
    @Value("${kafka.topic}")
    private String topic;

    @Bean
    @Primary
    public KafkaTemplate kafkaTemplate(){
        HashMap<String, Object> configs = new HashMap<>();
        configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrap_servers);
        configs.put(ProducerConfig.RETRIES_CONFIG,retries);
        configs.put(ProducerConfig.BATCH_SIZE_CONFIG,batch_size);
        configs.put(ProducerConfig.LINGER_MS_CONFIG,linger_ms);
        configs.put(ProducerConfig.BUFFER_MEMORY_CONFIG,buffer_memory);
        //configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,RoundRobinPartitioner.class);
        //设置序列化
        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class);
        //设置自定义分区
        DefaultKafkaProducerFactory producerFactory = new DefaultKafkaProducerFactory(configs);
        return new KafkaTemplate<String, String>(producerFactory);
    }


}
